package com.chen10.gobang.common.utils;

import com.chen10.gobang.common.constants.EmailConstants;
import com.chen10.gobang.common.enums.email.EmailTypeEnum;
import com.chen10.gobang.common.exception.BusinessException;
import com.chen10.gobang.config.AppConfig;
import lombok.RequiredArgsConstructor;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.util.Date;

@Component
@RequiredArgsConstructor
public class EmailUtil {
    @Resource
    private JavaMailSender javaMailSender;
    @Resource
    private AppConfig appConfig;

    @Resource
    private RedisUtil redisUtil;

    /**
     * 发送邮箱验证码
     * @param email
     * @param code
     */

    public void sendEmail(String email, String code, Integer type)
    {
        try{
            MimeMessage message = javaMailSender.createMimeMessage();

            MimeMessageHelper helper = new MimeMessageHelper(message, true);

            //设置邮箱标题内容
            String title = null;
            if(type.equals(EmailTypeEnum.REGISTER.getType())){
                title = EmailConstants.EMAIL_TITLE_REGISTER;
            }else{
                title = EmailConstants.EMAIL_TITLE_FORGET_PASSWORD;
            }
            helper.setFrom(appConfig.getSendUserName());
            helper.setTo(email);
            helper.setSubject(title);
            String emailContent = String.format(EmailConstants.EMAIL_CONTENT, code);

            helper.setText(emailContent);
            helper.setSentDate(new Date());

            //发送邮箱
            javaMailSender.send(message);

        }catch (Exception e){
            e.printStackTrace();
            throw new BusinessException(EmailConstants.EMAILCODE_SEND_ERROR);
        }

    }

    /**
     * 验证邮箱验证码
     * @param key
     * @param code
     * @return
     */
    public boolean verifyCode(String key , String code) {
        //查询缓存
        Object cacheCode = redisUtil.get(key);
        if (cacheCode == null) {
            return false;
        }

        if (code.equals(cacheCode.toString())) {
            // 验证成功后删除验证码
            redisUtil.delete(key);
            return true;
        }
        return false;
    }
}
